package com.example.demo.common;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: homechen
 * Date: 2024-03-11
 * Time: 22:27
 */

import com.example.demo.jwt.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后端，在这里使用 拦截器进行判断，请求报头中是否含有 token 字段
 * 如果有就 不进行拦截，不含有就进行拦截
 * 这里是一个普通的验证拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求中获取 token 字段
        String jwt_token = request.getHeader("user_token");
        Claims claims = JWTUtils.parseJWT(jwt_token); // 去验证token正确性
        if (claims != null) {
            log.info("获取令牌成功！");
            return true;
        }
        response.setStatus(401);
        return false; // 此时进行拦截
    }
}
